package com.DT.netTool;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class traceRoute {
    private static final String TAG = traceRoute.class.getSimpleName();
    private static final boolean IS_DEBUG = true;
    private Process process = null;
    private boolean Running = true;
    /**
     * //@param pingNetEntity 检测网络实体类
     */
    public boolean isRun(){
        if(Running == true)
            return false;
        else
            return true;
    }
    public void start(){
        Running=true;
    }
    public Process getProcess(){
        return process;
    }
    public void clearProcess(){
        process.destroy();
        Running=false;
    }
    public String getDstTime(String pingIP) {
        if(Running == false)return "killed";
        PingNetEntity pingNetEntity = new PingNetEntity(pingIP, 3, 0);
        String line = null;
        String timebuf = "";

        BufferedReader successReader = null;

        String command = "ping -c 3 -w 6 "+ pingIP;
        Log.w("trace",command);

//        String command = "ping -c " + pingCount + " " + host;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process == null) {
                debugLog("ping fail:process is null.");
                append(pingNetEntity.getResultBuffer(), "ping fail:process is null.");
                pingNetEntity.setPingTime(null);
                pingNetEntity.setResult(false);
                return "process null";
            }
            successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                debugLog(line);
                append(pingNetEntity.getResultBuffer(), line);

                if(line.contains("icmp_seq")) {
                    if(line.contains("time="))
                    timebuf+= line.substring(line.indexOf("time=")+5, line.indexOf("ms")+2)+" \t";
                    else
                        timebuf+="* \t";
                    Log.w("trace",timebuf);
                }

                /*发送到UI*/
//                if(line.contains("ms")) {
//                    Message sendMsg = new Message();
//                    sendMsg.what = 9999;
//                    sendMsg.obj = line + '\n';
//                    pingHandler.sendMessage(sendMsg);
//                }
                /*发送到UI*/
                String time;
                if ((time = getTime(line)) != null) {
                    pingNetEntity.setPingTime(time);
                }
            }
            int status = process.waitFor();
            if (status == 0) {
                debugLog("exec cmd success:" + command);
//                append(pingNetEntity.getResultBuffer(), "exec cmd success:" + command);
                pingNetEntity.setResult(true);
            } else {
                debugLog("exec cmd fail.");
//                append(pingNetEntity.getResultBuffer(), "exec cmd fail.");
                pingNetEntity.setPingTime(null);
                pingNetEntity.setResult(false);
            }
            debugLog("exec finished.");
//            append(pingNetEntity.getResultBuffer(), "exec finished.");
        } catch (IOException e) {
            debugLog(String.valueOf(e));
        } catch (InterruptedException e) {
            debugLog(String.valueOf(e));
        } finally {
            debugLog("ping exit.");
            if (process != null) {
                process.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
                    debugLog(String.valueOf(e));
                }
            }
        }
//        debugLog( pingNetEntity.getResultBuffer().toString());
        if(timebuf==null || timebuf.isEmpty() )return "* * *";
        return timebuf;
    }

    public String getIP(String pingIP,int TTL) {
        if(Running == false)return "killed";

        PingNetEntity pingNetEntity=new PingNetEntity(pingIP,1,0);
        String line = null;
        Process myprocess=null;
        String IPbuf="";

        BufferedReader successReader = null;
        String command;
        if (TTL == 0)command = "ping -c 1 -w 3 "+ pingNetEntity.getIp();
         else command = "ping -c 1 -t " + TTL + " -w 3 " + pingNetEntity.getIp();

        Log.w("trace",command);
//        String command = "ping -c " + pingCount + " " + host;
        try {
            myprocess = Runtime.getRuntime().exec(command);
            if (myprocess == null) {
                debugLog( "ping fail:process is null.");
                append(pingNetEntity.getResultBuffer(), "ping fail:process is null.");
                pingNetEntity.setPingTime(null);
                pingNetEntity.setResult(false);
                return "";
            }
            successReader = new BufferedReader(new InputStreamReader(myprocess.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                debugLog( line);
                append(pingNetEntity.getResultBuffer(), line);

                if (TTL == 0) {
                    if(line.contains("PING"))
                        IPbuf= line.substring(line.indexOf("(")+1, line.indexOf(")"));
                }
                else if(line.contains("icmp_seq"))
                {
                    if(line.contains("time="))
                        IPbuf= line.substring(line.indexOf("from ")+5, line.indexOf(":"));
                    else
                        IPbuf= line.substring(line.indexOf("From ")+5, line.indexOf(":"));
                    Log.w("trace",line);
                }

                String time;
                if ((time = getTime(line)) != null) {
                    pingNetEntity.setPingTime(time);
                }
            }
            int status = myprocess.waitFor();
            if (status == 0) {
                debugLog( "exec cmd success:" + command);
//                append(pingNetEntity.getResultBuffer(), "exec cmd success:" + command);
                pingNetEntity.setResult(true);
            } else {
                debugLog( "exec cmd fail.");
//                append(pingNetEntity.getResultBuffer(), "exec cmd fail.");
                pingNetEntity.setPingTime(null);
                pingNetEntity.setResult(false);
            }
            debugLog( "exec finished.");
//            append(pingNetEntity.getResultBuffer(), "exec finished.");
        } catch (IOException e) {
            debugLog( String.valueOf(e));
        } catch (InterruptedException e) {
            debugLog( String.valueOf(e));
        } finally {
            debugLog( "ping exit.");
            if (myprocess != null) {
                myprocess.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
                    debugLog( String.valueOf(e));
                }
            }
        }
        debugLog( pingNetEntity.getResultBuffer().toString());
        return IPbuf;
    }

    private static void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }

    static String getTime(String line) {
        String[] lines = line.split("\n");
        String time = null;
        for (String l : lines) {
            if (!l.contains("time="))
                continue;
            int index = l.indexOf("time=");
            time = l.substring(index + "time=".length());
            debugLog(time);
        }
        return time;
    }

    public static void debugLog(String content){
        if (IS_DEBUG){

            Log.d(TAG,content);
        }
    }


}


